package com.zpark.controller.exception;

import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaoyu
 * @version 1.0 2022/9/22
 */
//@RestController
@Controller
public class CustomExceptionHandlerController extends AbstractErrorController {
    // 定义错误映射路径
    private final static String ERROR_PATH = "/error";

    // 添加构造器
    public CustomExceptionHandlerController(ErrorAttributes errorAttributes) {
        // 调用父类构造器创建父类对象
        super(errorAttributes);
    }
    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

//    @RequestMapping(ERROR_PATH)
//    public Map<String, Object> customHandler(HttpServletRequest request) {
//        Map<String, Object> map = getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.MESSAGE));
//
//        Map<String, Object> result = new HashMap<>();
//        result.put("code", map.get("status"));
//        result.put("msg", map.get("error"));
//        return result;
//    }

    @RequestMapping(ERROR_PATH)
    public ModelAndView customHandler(HttpServletRequest request) {

        ModelAndView mv = new ModelAndView();
        mv.setViewName("404");
        Map<String, Object> map = getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.MESSAGE));

        Map<String, Object> result = new HashMap<>();
        result.put("code", map.get("status"));
        result.put("msg", map.get("error"));


        mv.addObject("result", result);
        return mv;
    }

}
